package com.sas.controller;

import com.sas.common.Result;
import com.sas.entity.SalaryInfo;
import com.sas.service.SalaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

/**
 * 薪资管理Controller
 */
@RestController
@RequestMapping("/salary")
@Validated
public class SalaryController {

    private static final Logger log = LoggerFactory.getLogger(SalaryController.class);
    @Autowired
    private SalaryService salaryService;

    /**
     * 创建薪资信息
     */
    @PostMapping
    public Result<SalaryInfo> createSalaryInfo(@Valid @RequestBody SalaryInfo salaryInfo) {
        log.info("创建薪资信息，等级: {}, 类型: {}", salaryInfo.getSalaryLevel(), salaryInfo.getEmployeeType());
        try {
            SalaryInfo savedSalaryInfo = salaryService.save(salaryInfo);
            return Result.success(savedSalaryInfo);
        } catch (Exception e) {
            log.error("创建薪资信息失败", e);
            return Result.error("创建薪资信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询薪资信息
     */
    @GetMapping("/{id}")
    public Result<SalaryInfo> getSalaryInfoById(@PathVariable Long id) {
        log.info("查询薪资信息，ID: {}", id);
        Optional<SalaryInfo> salaryInfo = salaryService.findById(id);
        if (salaryInfo.isPresent()) {
            return Result.success(salaryInfo.get());
        } else {
            return Result.notFound("薪资信息不存在");
        }
    }

    /**
     * 查询所有薪资信息
     */
    @GetMapping
    public Result<List<SalaryInfo>> getAllSalaryInfo(
            @RequestParam(required = false) Integer employeeType,
            @RequestParam(required = false, defaultValue = "false") Boolean onlyEffective) {
        log.info("查询薪资信息列表，员工类型: {}, 仅有效: {}", employeeType, onlyEffective);
        try {
            List<SalaryInfo> salaryInfoList;
            if (onlyEffective) {
                salaryInfoList = salaryService.findAllEffective();
            } else if (employeeType != null) {
                salaryInfoList = salaryService.findByEmployeeType(employeeType);
            } else {
                salaryInfoList = salaryService.findAll();
            }
            return Result.success(salaryInfoList);
        } catch (Exception e) {
            log.error("查询薪资信息列表失败", e);
            return Result.error("查询薪资信息列表失败: " + e.getMessage());
        }
    }

    /**
     * 更新薪资信息
     */
    @PutMapping("/{id}")
    public Result<SalaryInfo> updateSalaryInfo(@PathVariable Long id, @Valid @RequestBody SalaryInfo salaryInfo) {
        log.info("更新薪资信息，ID: {}", id);
        try {
            salaryInfo.setId(id);
            SalaryInfo updatedSalaryInfo = salaryService.update(salaryInfo);
            return Result.success(updatedSalaryInfo);
        } catch (Exception e) {
            log.error("更新薪资信息失败", e);
            return Result.error("更新薪资信息失败: " + e.getMessage());
        }
    }

    /**
     * 删除薪资信息
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteSalaryInfo(@PathVariable Long id) {
        log.info("删除薪资信息，ID: {}", id);
        try {
            salaryService.deleteById(id);
            return Result.success(null);
        } catch (Exception e) {
            log.error("删除薪资信息失败", e);
            return Result.error("删除薪资信息失败: " + e.getMessage());
        }
    }

    /**
     * 计算员工工资
     */
    @PostMapping("/calculate")
    public Result<BigDecimal> calculateSalary(
            @RequestParam Long employeeId,
            @RequestParam Double workHours,
            @RequestParam(required = false, defaultValue = "false") Boolean isNightShift,
            @RequestParam(required = false, defaultValue = "false") Boolean isWeekend,
            @RequestParam(required = false, defaultValue = "false") Boolean isHoliday,
            @RequestParam(required = false, defaultValue = "0") Double overtimeHours) {
        log.info("计算员工工资，员工ID: {}, 工作时长: {}", employeeId, workHours);
        try {
            BigDecimal salary = salaryService.calculateSalary(employeeId, workHours, 
                    isNightShift, isWeekend, isHoliday, overtimeHours);
            return Result.success(salary);
        } catch (Exception e) {
            log.error("计算员工工资失败", e);
            return Result.error("计算员工工资失败: " + e.getMessage());
        }
    }

    /**
     * 计算员工某时间段的总工资
     */
    @GetMapping("/total/{employeeId}")
    public Result<BigDecimal> calculateTotalSalary(
            @PathVariable Long employeeId,
            @RequestParam String startDate,
            @RequestParam String endDate) {
        log.info("计算员工总工资，员工ID: {}, 时间段: {} - {}", employeeId, startDate, endDate);
        try {
            BigDecimal totalSalary = salaryService.calculateTotalSalary(employeeId, startDate, endDate);
            return Result.success(totalSalary);
        } catch (Exception e) {
            log.error("计算员工总工资失败", e);
            return Result.error("计算员工总工资失败: " + e.getMessage());
        }
    }

    /**
     * 计算房间某时间段的总工资成本
     */
    @GetMapping("/room-cost/{roomId}")
    public Result<BigDecimal> calculateRoomSalaryCost(
            @PathVariable Long roomId,
            @RequestParam String startDate,
            @RequestParam String endDate) {
        log.info("计算房间工资成本，房间ID: {}, 时间段: {} - {}", roomId, startDate, endDate);
        try {
            BigDecimal roomCost = salaryService.calculateRoomSalaryCost(roomId, startDate, endDate);
            return Result.success(roomCost);
        } catch (Exception e) {
            log.error("计算房间工资成本失败", e);
            return Result.error("计算房间工资成本失败: " + e.getMessage());
        }
    }

    /**
     * 获取工资对比数据
     */
    @GetMapping("/comparison")
    public Result<Object> getSalaryComparison(
            @RequestParam String startDate,
            @RequestParam String endDate,
            @RequestParam String compareStartDate,
            @RequestParam String compareEndDate) {
        log.info("获取工资对比数据，当前时间段: {} - {}, 对比时间段: {} - {}", 
                startDate, endDate, compareStartDate, compareEndDate);
        try {
            Object comparison = salaryService.getSalaryComparison(startDate, endDate, compareStartDate, compareEndDate);
            return Result.success(comparison);
        } catch (Exception e) {
            log.error("获取工资对比数据失败", e);
            return Result.error("获取工资对比数据失败: " + e.getMessage());
        }
    }
}